package com.lihonghao.handle;

import com.lihonghao.controller.spring.SendController;
import com.lihonghao.utils.RedisUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.SocketAddress;

@Service
@ChannelHandler.Sharable
public class HttpForwardHandler extends ChannelInboundHandlerAdapter {
    @Resource
    RedisUtil redisUtil;
    public static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private Logger logger = LoggerFactory.getLogger(HttpForwardHandler.class);
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof String){
            String str = ((String) msg).trim();
            System.out.println(str);
            if (str.startsWith("back")){
                redisUtil.set("back",str);
                ctx.fireChannelReadComplete();
            }
        }
        ctx.channel().writeAndFlush("接收消息 => "+((String) msg).trim()).addListener(future -> {
            if (future.cause() != null) {
                logger.error("netty消息发送失败:", future.cause());
            } else if (future.isSuccess()) {
                logger.info("netty消息发送成功至客户端 :{}", "test");
            } else {
                logger.error("Message send failed for an unknown reason.");
            }
        });
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.add(channel);
        SocketAddress remoteAddress = channel.remoteAddress();
        redisUtil.set("http_forward_channel",remoteAddress);
        System.out.println("in");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.remove(channel);
        System.out.println("out");
    }
}